package org.finesys.common.log.trace.interceptor.hutoolhttpclient;

import static org.finesys.common.log.constants.TraceConstants.PARENT_ID;
import static org.finesys.common.log.constants.TraceConstants.SPAN_ID;
import static org.finesys.common.log.constants.TraceConstants.TRACE_ID;

import org.finesys.common.log.trace.interceptor.AbstractInterceptor;
import org.finesys.common.log.trace.util.LogstashUtil;
import org.springframework.util.StringUtils;

import cn.hutool.http.HttpBase;
import cn.hutool.http.HttpInterceptor;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class TraceIdHutoolHttpClientInterceptor extends AbstractInterceptor implements HttpInterceptor {

    @Override
    public void process(HttpBase httpBase) {
        try {
            if (StringUtils.hasText(getTraceId())) {
                httpBase.header(TRACE_ID, getTraceId());
                httpBase.header(SPAN_ID, getSpanId());
                httpBase.header(PARENT_ID, getParentId());
            } else {
                if (log.isInfoEnabled()) {
                    log.info(LogstashUtil.marker(), "current thread have not the traceId!");
                }
            }
        } catch (Exception e) {
            if (log.isErrorEnabled()) {
                log.error(LogstashUtil.exceptionMarker(), "HttpClient http header set traceId exception!", e);
            }
        }
    }
}
